<?php 

namespace app\controller\appPage;

use app\exception\ErrnoPlus;
use app\service\AppInfoTableService;
use app\validate\AppInfoTableValidate;
use share\controller\PageBaseController;
use share\exception\PageException;
use share\service\ContextService;
use share\utils\Helper;

class AppInfoTableController extends PageBaseController{

    public function initValidate(){  
        $this->validate = new AppInfoTableValidate();
    }

    /**
     * 跳转接口 无返回
     */
    public function get_download_action(){
  
        $vendor = $this->request->param("vendor"); 
        $errMsg = lang("App download not available");
        if(empty($vendor)){
            echo "<script>alert('" . $errMsg . "')</script>";
            echo "<h1>" . $errMsg. "</h1>";
            exit();
        }
        $url = AppInfoTableService::getDownloadUrlByVendor($vendor,ContextService::getIP());
        if(empty($url)){
            echo "<script>alert('" . $errMsg . "')</script>";
            echo "<h1>" . $errMsg. "</h1>";
            exit();
        }
        header("Location: ".$url,TRUE,302);// 302 临时跳转 301 永久转移
        // 不支持头部跳转时
        echo "<script>location.href='" . $url . "'</script>";
        exit();
    }

    /**
     * 隐私协议
     */
    public function privacy_action(){
        $input = $this->check();
        $info = self::getRealAppInfo($input);
        $lang = self::getRenderLanguage($input['language']);
        $tpl = 'privacy_'.$lang.'.html';   
        return self::ok(['info'=>$info],$tpl);
    }

    public function user_agreement_action(){
        $input = $this->check();
        $info = self::getRealAppInfo($input);
        $lang = self::getRenderLanguage($input['language']);
        $tpl = 'user_agreement_'.$lang.'.html';   
        return self::ok(['info'=>$info],$tpl);
    }

    public static function getRealAppInfo($input){
        $info = AppInfoTableService::getPrivacy($input);
        if(empty($info)){
            throw new PageException("request forbidden",ErrnoPlus::NOT_BACK_DATA);
        }
        //特殊处理 
        if($info['package'] === 'com.lecooit.lceapp' && isset($_SERVER['HTTP_USER_AGENT']) && Helper::getClientTypeByUserAgent($_SERVER['HTTP_USER_AGENT']) === Helper::CLIENT_TYPE_OF_IOS){
            $info['app_cn'] = 'Lecoo';
            $info['app_en'] = 'Lecoo';
        }
        return $info;
    }

    public static function getRenderLanguage($language){
        $lang = 'EN';
        $language = strtoupper($language);
        if($language){
            if(strpos($language,'CN') !== false || strpos($language,'ZH') !== false){
                $lang = 'CN';
            }
            else if(strpos($language,'TW') !== false){
                $lang = 'TW';
            }          
        }
        return $lang;
    }


}